/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package de.sisoft.timera.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;

import de.sisoft.timera.dao.IUserDao;
import de.sisoft.timera.entity.Employee;
import de.sisoft.timera.entity.Project;
import de.sisoft.timera.exception.UserNotFoundException;

/**
 *
 * @author Christian Hildebrandt
 */
public class UserDao extends BaseDao implements IUserDao {

    @Override
    public List<Employee> getAllUsers() {
	final EntityManager em = getEntityManager();
	final Query query = em.createNamedQuery("Employee.findAll", Employee.class);
	final List<Employee> allUsers = query.getResultList();
	em.close();
	return allUsers;
    }

    @Override
    public Employee getUserById(final long id) throws UserNotFoundException {
	final EntityManager em = getEntityManager();
	Employee userById;
	try {
	    userById = em.createNamedQuery("Employee.findEmployeeById", Employee.class).setParameter("id", id)
		    .getSingleResult();

	} catch (final NoResultException nre) {
	    throw new UserNotFoundException(nre.getLocalizedMessage());
	}
	em.close();
	return userById;
    }

    @Override
    public Employee getUserByUsername(final String name) throws UserNotFoundException {
	final EntityManager em = getEntityManager();
	Employee userByUsername;
	try {
	    userByUsername = em.createNamedQuery("Employee.findEmployeeByUsername", Employee.class)
		    .setParameter("username", name).getSingleResult();

	} catch (final NoResultException nre) {
	    throw new UserNotFoundException(nre.getLocalizedMessage());
	}
	em.close();
	return userByUsername;
    }

    @Override
    public void addUser(final Employee user) {
	super.createOrUpdate(user);
    }

    @Override
    public void updateUser(final Employee user) {
	super.update(user);
    }

    @Override
    public void deleteUser(final Employee user) {
	super.delete(user);
    }

    @Override
    public List<Project> getProjectsForEmployee(final Employee employee) {
	final EntityManager em = getEntityManager();
	final List<Project> projectsByUsername = em.createNamedQuery("Project.findProjectByEmployee", Project.class)
		.setParameter("associate", employee).getResultList();
	em.close();
	return projectsByUsername;
    }

}
